package com.llh.demo4shiro.controller;

import com.llh.demo4shiro.model.Role;
import com.llh.demo4shiro.model.User;
import com.llh.demo4shiro.service.UserService;
import com.llh.demo4shiro.vo.JsonResult;
import com.llh.demo4shiro.vo.UserRoles;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * <p>CreatedAt: 2020/9/16 15:51</p>
 *
 * @author llh
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("register")
    public JsonResult register(@RequestBody User user) {

        JsonResult result = new JsonResult();
        if (userService.existedUsername(user.getUsername())) {
            result.setOk(false)
                    .setMsg("用户名已存在");
            return result;
        }

        User register = userService.register(user);

        return result.setOk(true).setData(register);
    }

    @GetMapping("all")
    public JsonResult all() {
        List<User> all = userService.all();
        JsonResult result = new JsonResult();
        return result
                .setCode(0)
                .setData(all);
    }

    @GetMapping("get/role/{id}")
    public JsonResult getRole(@PathVariable Integer id) {
        List<Role> list = userService.getRoles(id);
        return new JsonResult()
                .setCode(0)
                .setData(list);
    }

    @PostMapping("add/role")
    public JsonResult addRole(@RequestBody UserRoles userRoles) {
        int addRoles = userService.addRoles(userRoles);
        return new JsonResult()
                .setCode(0)
                .setData(addRoles);
    }

    @PostMapping("login")
    @RequiresGuest
    public ModelAndView login(User user, ModelAndView mv) {
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setPassword(user.getPassword().toCharArray());
        token.setUsername(user.getUsername());
        try {
            SecurityUtils.getSubject().login(token);
            mv.setViewName("hello");
            mv.addObject("username", user.getUsername());
        } catch (AuthenticationException e) {
            e.printStackTrace();
            mv.setViewName("error");
            mv.addObject("msg", "登录失败！");
        }
        return mv;
    }

    @GetMapping("logout")
    public ModelAndView logout(ModelAndView mv) {
        SecurityUtils.getSubject().logout();
        mv.setViewName("redirect:/");
        return mv;
    }

}
